<template>
<view class="page__bd">
	<custom-navbar bgColor="bg-white shadow" :isBack="true" :transparent="true">
		<block slot="backText">返回</block>
		<block slot="content">登陆</block>
	</custom-navbar>
	<view class="site-wrap" :style="[{paddingTop:(CustomBar + 30) + 'px'}]">
		<view class="padding-tb-lg" style="filter: drop-shadow(0 0 10px rgba(0,0,0,0.1));">
			<image :src="danceData.webURL+'/appres/icon108.png'" mode="widthFix" style="width:140rpx"></image>
		</view>
		<view class="colBox">
			<view class="colMain">
				<view class="login-box text-left" v-if="type == 1">
					<view class="login-box-item">
						<form :report-submit="true" @submit="formLogin">
							<view class="login-title text-primary">
								登录
							</view>
							<view class="daui-cell login-cell bg-primary-light">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-mobilefill text-primary"></text>
								</view>
								<view class="daui-cell__bd">
									<input type="text" name="username" value="" placeholder="请输入您的用户名/手机号码" />
								</view>
							</view>
							<view class="daui-cell login-cell bg-primary-light">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-lock text-primary"></text>
								</view>
								<view class="daui-cell__bd">
									<input :type="isShowPassWord?'text':'password'" name="password" value="" placeholder="请输入您的密码" />
								</view>
								<view class="daui-cell__ft" @tap="togglePassword">
									<text :class="isShowPassWord?'icon-attentionfill':'icon-attentionforbidfill'"></text>
								</view>
							</view>
							<view class="daui-cell">
								<view class="daui-cell__bd">
									<navigator url="/pagesA/user/forgetpwd" class="flex-sub text-sm text-right">
										忘记密码？
									</navigator>
								</view>
							</view>
							<view class="daui-cell daui-cell_agree padding-no">
								<view class="daui-cell__hd">
									<evan-checkbox v-model="agreementChecked" shape="round">
										阅读并同意
									</evan-checkbox>
								</view>
								<view class="daui-cell__bd">
									<view @tap="showAgreement">《用户协议及隐私条款》</view>
								</view>
							</view>
							<view class="margin-top">
								<button class="daui-btn daui-btn_primary daui-btn_block round shadow" form-type="submit">登录</button>
							</view>
						</form>
					</view>
					<view class="login-box-itemtwo" @tap="changgeType" style="display: none;">
						还没有账号？ <text class="text-orange">立即注册</text>
					</view>
					<view class="login-box-itemtwo">
						<!-- #ifdef APP-PLUS -->
						<view class="foot" v-if="isShowThirdlogin">
							<view class="flex">
								<view class="flex-sub">
									<button class="daui-btn bg-green round" style="width:130pt, height:30pt, corner radius: 6pt" @tap="weixinLoginAppPlus">
										<text class="iconfontzz icon-weixin margin-right-sm"></text>微信登录
									</button>
								</view>
								<view class="flex-sub" v-if="platform == 'ios'">
									<button class="daui-btn bg-black round" style="width:130pt, height:30pt, corner radius: 6pt" @tap="appleLoginAppPlus">
										<text class="iconfontzz icon-apple margin-right-sm"></text>通过Apple登录
									</button>
								</view>
							</view>
						</view>
						<!-- #endif -->
						
						<!-- #ifdef H5 -->
						<view class="foot">
							<view class="flex">
								<view class="flex-sub">
									<button class="daui-btn bg-green round" style="width:130pt, height:30pt, corner radius: 6pt" @tap="weixinLoginH5">
										<text class="iconfontzz icon-weixin margin-right-sm"></text>微信登录
									</button>
								</view>
								<view class="flex-sub" v-if="0">
									<button class="daui-btn bg-black round" style="width:130pt, height:30pt, corner radius: 6pt" @tap="appleLoginAppPlus">
										<text class="iconfontzz icon-apple margin-right-sm"></text>通过Apple登录
									</button>
								</view>
							</view>
						</view>
						<!-- #endif -->
						
						<!-- #ifdef MP-WEIXIN -->
						<view class="foot" v-if="0">
							<view class="flex">
								<view class="flex-sub">
									<button class="daui-btn bg-green round" style="width:130pt, height:30pt, corner radius: 6pt" @click="weixinLoginMp">
										<text class="iconfontzz icon-weixin margin-right-sm"></text>手机号快捷登录
									</button>
								</view>
							</view>
						</view>
						<!-- #endif -->
					</view>
				</view>
				<view class="login-box padding-lr-xl0 text-left" v-if="type == 2">
					<view class="login-box-item">
						<form :report-submit="true" @submit="formRegister">
							<view class="login-title">
								注册
							</view>
							<view class="daui-cell login-cell">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-mobilefill"></text>
								</view>
								<view class="daui-cell__bd">
									<input type="number" name="company" v-model="company" placeholder="请输入公司名称" />
								</view>
							</view>
							<view class="daui-cell login-cell">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-mobilefill"></text>
								</view>
								<view class="daui-cell__bd">
									<input type="number" name="mobile" v-model="mobile" placeholder="请输入您的手机号码" />
								</view>
							</view>
							<view class="daui-cell login-cell" v-if="isShowMobilecode">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-safe"></text>
								</view>
								<view class="daui-cell__bd">
									<input type="number" name="code" :value="mobilecode" placeholder="短信验证码" @input="bindCodeInput"></input>
								</view>
								<view class="daui-cell__ft">
									<view class="text-primary" @tap="sendMobileCode" :disabled="timeOut">{{timeText}}</view>
								</view>
							</view>
							<view class="daui-cell login-cell" style="display: none;">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-lock"></text>
								</view>
								<view class="daui-cell__bd">
									<input :type="isShowPassWord?'text':'password'" name="password" value="" placeholder="请设置您的登录密码" />
									<view class="action" @tap="togglePassword">
										<text :class="isShowPassWord?'icon-attentionfill':'icon-attentionforbidfill'"></text>
									</view>
								</view>
							</view>
							<view class="daui-cell login-cell" style="display: none;">
								<view class="daui-cell__hd">
									<text class="iconfontzz icon-tuijian"></text>
								</view>
								<view class="daui-cell__bd">
									<input type="text" name="referralcode" value="" placeholder="推荐码(选填)" />
								</view>
							</view>
							<view class="login-gap">
								<view class="login-gap-lr"></view>
							</view>
							<view class="">
								<button class="daui-btn daui-btn_primary daui-btn_block round shadow" form-type="submit">立即注册</button>
							</view>
						</form>
					</view>
					<view class="login-box-itemtwo" @tap="changgeType">
						已有账号？ <text class="text-orange">立即登录</text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="padding-lr-xl account-tip" v-if="0">
			<view class="account-tip-tit"></view>
			<view class="account-tip-desc">
				<text class="text-brown">登录</text>：加盟商及会员可使用手机号密码直接登录、或者使用第三方授权登录
			</view>
			<view class="account-tip-desc">
				<text class="text-brown">注册</text>：注册后等待管理员审核即可
			</view>
		</view>
		
	</view>
	
	<!-- 协议弹出框 -->
	<uni-popup ref="agreementPopup" :type="popupType" :animation="false">
		<view class="daui-fullpopup">
			<view class="daui-fullpopup__bd">
				<scroll-view scroll-y="true" class="daui-fullpopup__bd bg-white">
					<mp-html :content="agreementContent" lazy-load="true" :tag-style="tagStyle">协议详情展示</mp-html>
				</scroll-view>
			</view>
			<view class="daui-fullpopup__ft">
				<button class="daui-btn bg-cyan block" @click="doAgree">我已阅读并同意此协议</button>
			</view>
		</view>
	</uni-popup>
	
	<!--toast提示-->
	<daui-toast ref="toast"></daui-toast>
</view>
</template>

<script>
import danceuiTool from '../../utils/danceuiTool';
import http from "../../server/api-mine.js"
import { mapMutations } from 'vuex';
import mpHtml from '@/components/mp-html/mp-html'
export default {
	components:{
		mpHtml
	},
	name: 'login',
	data() {
		return {
			StatusBar: this.StatusBar,
			CustomBar: this.CustomBar,
			danceData: this.danceData,
			platform: '',
			appid: '',
			list_param:{},
			is_send:true,
			subtitleText: 'subtitleText',
			nbLoading: false,
			nbFrontColor: '#000000',
			nbBackgroundColor: '#ffffff',
			isShowPassWord: false,
			isShowThirdlogin: true,
			isShowMobilecode: true,
			type: 1,
			oauthId: 0,
			mobile: '',
			tmpFlag: '0',
			mobilecode: '',
			timeOut: false,
			timeText: '发送验证码',
			timeNum: 30,
			tagStyle: {},
			popupType: 'bottom',
			agreementChecked: false,
			agreementContent: '',
		}
	},
	onLoad(options) {
		//#ifdef H5
		//H5登陆作用
		let code = this.getUrlCode('code')
		if(code !== null || code !== "") {
			this.getOpenidAndUserinfo(code);
		}
		//#endif
		
		var that = this;
		uni.getSystemInfo({
			success: function(res) {
				that.platform = res.platform;
			}
		})
		this.getData();
	},
	methods: {
		...mapMutations(["qsLogin"]),
		async getData(){ //请求并获取数据
			const token = uni.getStorageSync('token');
			let headers = {"Authorization":"Bearer "+token};
			let ret = await http.login(this.$refs.toast, this.list_param, headers);
			var retData = ret.data;
			//console.log('login页面,获取到的数据：', retData);
			this.appid = retData.appid;
			console.log('=====当前平台platform:', this.platform);
			if (uni.getSystemInfoSync().platform == "ios") { //ios下隐藏第三方登陆
				if(retData.configInfo.thirdlogin_open == 0){
					this.isShowThirdlogin = false;
				}
			}
			if(retData.configInfo.mobilecode_open == 0){
				this.isShowMobilecode = false;
			}
		},
		popupState(state) {
			console.log('popupState:', state);
			if(state == false){
				danceuiTool.showToast(this.$refs.toast, '请先同意服务协议再进行操作');
			}
		},
		verificationLogin(e){
			if(!e.detail.value.username.trim()){
				uni.showToast({
					icon:"none",
					title:"用户名/手机号不能为空"
				})
				this.is_send = false
			}else if(!e.detail.value.password){
				uni.showToast({
					icon:"none",
					title:"密码不能为空"
				})
				this.is_send = false
			}else{
				this.is_send = true
			}
		},
		async formLogin(e){
			if(this.agreementChecked == false){
				danceuiTool.showToast(this.$refs.toast, '请先阅读用户协议及隐私政策', 'info');
				return;
			}
			this.verificationLogin(e);
			if(this.is_send){
				let formdata = e.detail.value;
				this.list_param = {...this.list_param,...formdata};
				let headers = {"content-type":"application/x-www-form-urlencoded"};
				let ret = await http.doLogin(this.$refs.toast, this.list_param, headers);
				console.log('login页面，获取到的数据：', ret);
				if(ret.code == 200){
					var retData = ret.data;
					this.qsLogin(retData.token);
					danceuiTool.showToast(this.$refs.toast, ret.msg);
					const app = getApp();
					app.globalData.first = 1;
					setTimeout(() => {
						uni.switchTab({
							url:"/pages/mine/mine"
						})
					}, 1000)
				}
			}
		},
		verificationRegister(e){
			if(!e.detail.value.username.trim()){
				uni.showToast({
					icon:"none",
					title:"用户名/手机号不能为空"
				})
				this.is_send = false
			}else if(!e.detail.value.password){
				uni.showToast({
					icon:"none",
					title:"密码不能为空"
				})
				this.is_send = false
			}else{
				this.is_send = true
			}
		},
		async formRegister(e){
			this.verificationRegister(e);
			if(this.is_send){
				let formdata = e.detail.value;
				formdata.oauthId = this.oauthId;
				this.list_param = {...this.list_param,...formdata};
				console.log('this.list_param:', this.list_param);
				let headers = {"content-type":"application/x-www-form-urlencoded"};
				let ret = await http.doRegister(this.$refs.toast, this.list_param, headers);
				console.log('doRegister操作，获取到的数据：', ret);
				var retData = ret.data;
				try{
					if(retData){
						this.qsLogin(retData.token);
						danceuiTool.showToast(this.$refs.toast, retData.msg, 1);
						const app = getApp();
						app.globalData.first = 1;
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							})
						}, 1000)
					}
				}catch(e){
					//TODO handle the exception
				}
			}
		},
		togglePassword() {
			this.isShowPassWord = !this.isShowPassWord
		},
		changgeType() {
			this.type = this.type == 1 ? this.type = 2 : this.type = 1;
		},
		async sendMobileCode(){
			console.log('=====发送验证码,sendMobileCode');
			if (this.mobile == '' || this.mobile == null) {
				danceuiTool.showToast(this.$refs.toast, '请输入手机号码')
				return;
			}
			var param = {
				mobile: this.mobile
			};
			let headers = {"content-type":"application/x-www-form-urlencoded"};
			let ret = await http.sendMobileCode(this.$refs.toast, param, headers);
			var retData = ret.data;
			if(typeof retData != "undefined"){
				let that = this;
				danceuiTool.showToast(this.$refs.toast, '验证码已发送')
				that.timeOut = true
				that.TimeOutDown();
			}
		},
		TimeOutDown() {
			let that = this;
			setTimeout(function(){
				if (that.timeNum > 0) {
					let text = '稍等' + that.timeNum + '秒';
					that.timeText = text;
					that.timeNum = that.timeNum - 1
					that.TimeOutDown();
				} else {
					that.timeOut = false;
					that.timeText = '获取验证码';
					that.timeNum = 30
				}
			}, 1000);
		},
		//#ifdef APP-PLUS
		weixinLoginAppPlus(){
			console.log('=====wxLoginAppPlus开始');
			var that = this;
			uni.login({
				provider: 'weixin',
				success: function (loginRes) {
					console.log('loginRes.authResult:', loginRes.authResult);
					//danceuiTool.showToast('loginRes.authResult:'+loginRes.authResult);
					// 获取用户信息
					uni.getUserInfo({
						provider: 'weixin',
						success: function (infoRes) {
							//danceuiTool.showToast('用户昵称为：' + infoRes.userInfo.nickName);
							//danceuiTool.showToast(JSON.stringify(infoRes.userInfo));
							console.log('获取到的用户信息:', JSON.stringify(infoRes.userInfo));
							that.weixinLoginAppPlusTwo(infoRes.userInfo);
						}
					});
				}
			});
		},
		async weixinLoginAppPlusTwo(userInfo) {
			if (userInfo) {
				let param = {
					openid: userInfo.openId,
					unionid: userInfo.unionId,
					nickname: userInfo.nickName,
					gender: userInfo.gender,
					city: userInfo.city,
					province: userInfo.province,
					country: userInfo.country,
					avatar: userInfo.avatarUrl,
				}
				//danceuiTool.showToast(JSON.stringify(param));
				let ret = await http.weixinLoginAppPlus(this.$refs.toast, param);
				var retData = ret.data;
				console.log('weixinLoginAppPlus,retData:', JSON.stringify(retData));
				//danceuiTool.showToast(JSON.stringify(retData));
				try{
					this.qsLogin(retData.token);
					//danceuiTool.showToast('loginApp,token:'+retData.token);
					if(retData){
						const app = getApp();
						app.globalData.first = 1;
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}catch(e){
					//TODO handle the exception
				}
			}
		},
		appleLoginAppPlus(){
			console.log('=====appleLoginAppPlus开始');
			var that = this;
			uni.login({
				provider: 'apple',
				success: function (loginRes) {
					console.log('loginRes:', JSON.stringify(loginRes));
					//danceuiTool.showToast('loginRes:'+JSON.stringify(loginRes));
					// 获取用户信息
					uni.getUserInfo({
						provider: 'apple',
						success: function (infoRes) {
							console.log('获取到的用户信息:', JSON.stringify(infoRes.userInfo));
							//danceuiTool.showToast('获取到的用户信息:', JSON.stringify(infoRes.userInfo));
							that.appleLoginAppPlusTwo(infoRes.userInfo);
						}
					});
				},
				fail: function (err) {
					// 登录失败
					console.log('登陆失败,err:', JSON.stringify(err));
					danceuiTool.showToast('登陆失败:'+JSON.stringify(err));
				}
			});
		},
		async appleLoginAppPlusTwo(userInfo) {
			if (userInfo) {
				let param = {
					openId: userInfo.openId,
					familyName: userInfo.fullName.familyName,
					giveName: userInfo.fullName.giveName,
					givenName: userInfo.fullName.givenName,
					email: userInfo.email,
					realUserStatus: userInfo.realUserStatus
				}
				//danceuiTool.showToast(JSON.stringify(param));
				let ret = await http.appleLoginAppPlus(this.$refs.toast, param);
				var retData = ret.data;
				console.log('appleLoginAppPlus,retData:', JSON.stringify(retData));
				//danceuiTool.showToast(JSON.stringify(retData));
				try{
					this.qsLogin(retData.token);
					//danceuiTool.showToast('loginApp,token:'+retData.token);
					if(retData){
						const app = getApp();
						app.globalData.first = 1;
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}catch(e){
					//TODO handle the exception
				}
			}
		},
		//#endif
		//#ifdef H5
		weixinLoginH5(){
			console.log('=====weixinLoginH5开始');
			if(this.agreementChecked == false){
				danceuiTool.showToast(this.$refs.toast, '请先阅读用户协议及隐私政策');
				return;
			}
			let curRoute  = this.$mp.page.route; //直接获取当前页面路由
			//console.log('weixinLoginH5,curRoute:'+curRoute);
			//weixinLoginH5,curRoute:pages/user/login
			//return;
			//var curRoute = 'pages/user/login';
			let origin = this.danceData.webURL+'/h5/#/'+curRoute //网页授权的回调域名，这里设置的是本地端口
			let urlNow = encodeURIComponent(origin); //处理域名
			let scope = "snsapi_userinfo"; //弹框显示授权
			let appid = this.danceData.wechatAppid;
			let code = this.getUrlCode('code');
			//danceuiTool.showToast('weixinLoginH5,code:'+code);
			// 截取code
			if(code == null || code === ''){ //未授权去授权
				let url =
				`https://open.weixin.qq.com/connect/oauth2/authorize?
				appid=${appid}&redirect_uri=${urlNow}&
				response_type=code&scope=${scope}&
				state=123#wechat_redirect`;
				window.location.href = url;
			}else{
				this.getOpenidAndUserinfo(code);
			}
		},
		getUrlCode(name) {
			if(this.tmpFlag == '1'){
				return '';
			}
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
		},
		async getOpenidAndUserinfo(code) { // 拿code换取accessToken和openid最后获取用户信息
			if (code) {
				//danceuiTool.showToast('', 'getOpenidAndUserinfo,code:'+code);
				let param = {
					code: code
				}
				let ret = await http.weixinLoginH5(this.$refs.toast, param);
				var retData = ret.data;
				console.log('weixinLoginH5操作,retData:', JSON.stringify(retData));
				//if(typeof retData != "undefined"){
				this.tmpFlag = '1';
				//}
				try{
					//danceuiTool.showToast('getOpenidAndUserinfo,token:'+retData.token);
					this.qsLogin(retData.token);
					if(retData){
						const app = getApp();
						app.globalData.first = 1;
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}catch(e){
					//TODO handle the exception
				}
			}
		},
		//#endif
		//#ifdef MP-WEIXIN
		weixinLoginMp() {
			console.log('=====weixinLoginMp开始');
			if(this.agreementChecked == false){
				danceuiTool.showToast(this.$refs.toast, '请先阅读用户协议及隐私政策');
				return;
			}
			var that = this;
			//1.wx获取登录用户code
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					let code = loginRes.code;
					console.log('用户登录的code:', code);
					that.weixinLoginMpTwo(code);
				},
				fail: function(res) {
					danceuiTool.showToast(this.$refs.toast, '您取消了授权登陆');
				},
			});
		},
		async weixinLoginMpTwo(code) {
			let param = {
				code: code,
			}
			let ret = await http.weixinLoginMp(this.$refs.toast, param);
			if(ret.code == 200){
				var retData = ret.data;
				if(retData.uid == 0){
					this.type = 2;
					this.oauthId = retData.oauthId;
				}else{ //存在账户，登陆成功
					console.log('weixinLoginMp,retData:', JSON.stringify(retData));
					//danceuiTool.showToast(JSON.stringify(retData));
					try{
						this.qsLogin(retData.token);
						//danceuiTool.showToast('loginApp,token:'+retData.token);
						if(retData){
							const app = getApp();
							app.globalData.first = 1;
							uni.switchTab({
								url: '/pages/mine/mine'
							})
						}
					}catch(e){
						//TODO handle the exception
					}
				}
			}
		},
		//#endif
		bindCodeInput(e) {
			this.code = e.detail.value
		},
		async showAgreement(){ //请求并获取数据
			console.log('showAgreement');
			let ret = await http.explain(this.$refs.toast, {'type': 'privacypolicy'});
			var retData = ret.data;
			console.log('explain操作，获取到的数据：', retData);
			this.popupType = 'bottom';
			this.$refs.agreementPopup.open();
			this.agreementContent = retData.content;
		},
		doAgree(){
			this.$refs.agreementPopup.close();
			this.agreementChecked = true;
			console.log('doAgree,agreementChecked:', this.agreementChecked);
		},
	}
}
</script>

<style>
.site-wrap{text-align:center;}
.colBox{width:100%}
.colMain{width:100%;display:flex;}
.colMain>view{flex:1}

.login-box{}
.login-box-item{margin:0 68rpx;padding:20rpx 40rpx 40rpx;background-color: #ffffff;border-radius: 16rpx;}
.login-box-itemtwo{margin:0 68rpx;text-align: center;padding: 40rpx 0 20rpx;}
.login-box .login-title{text-align:center;margin: 15rpx 0 25rpx;}
.login-box .daui-cell.login-cell{margin-bottom:20rpx;border-radius:48rpx}
.login-box .daui-cell.login-cell .daui-cell__hd{width:40rpx}
.login-box .daui-cell:before{border:none}
.login-box .daui-cell.login-cell .iconfontzz{}

.account-tip{text-align:left;padding:20rpx;position: fixed;bottom: 22rpx;}
.account-tip-tit{color: #f37b1d;font-size: 30rpx;}
.account-tip-desc{color: #bbbbbb;font-size: 24rpx;}
.account-tip-desc text{color: #f37b1d}
</style>
